<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\widgets\ActiveForm;
use kartik\widgets\DatePicker;

//use mdm\admin\components\AccessControl;
/* @var $this yii\web\View */
/* @var $searchModel ua_backend\models\search\UserSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = $title;
$this->params['breadcrumbs'][] = ['label'=>'意见反馈','url'=>['/user/notes']];
$this->params['breadcrumbs'][] = $this->title;

?>

    <div class="box">
        <?= GridView::widget([
            'dataProvider' => $dataProvider,
            'layout' => '<div class="box-body">{items}</div>
                         <div class="box-footer">
                            {summary}
                            <div class="_pager">{pager}</div>
                         </div>',

            'columns' => [
                [
                    'attribute' => 'id',
                    'enableSorting' => false,
                    'label' => 'ID',
                ],
                [
                    'attribute' => 'user.id',
                    'enableSorting' => false,
                    'label' => 'UID',
                ],

                [
                    'attribute' => 'user.avatar',
                    'format' => ['image',['width'=>'40','height'=>'40']],
                    'label' => Yii::t('app', 'Avatar'),
                    'enableSorting' => false,
                    'value' => function ($model){
                        if(substr($model->user->avatar,0,4)=='http'){
                            return $model->user->avatar;
                        }else{
                            return FILE_PATH.$model->user->avatar;
                        }
                    }
                ],

                [
                    'attribute' => 'user.nickname',
                    'label' => Yii::t('app', 'Nickname'),
                    'enableSorting' => false,
                    'contentOptions' => ['width'=>'15%'],
                    'value' => function ($model) {
                        try {
                            if(!json_decode($model->user->nickname)){
                                throw new Exception();
                            }else{
                                $nickname = json_decode($model->user->nickname);
                            }
                        }catch (Exception $e){
                            $nickname = urldecode($model->user->nickname);
                        }
                        return $nickname;
                    }
                ],

                [
                    'attribute' => 'note',
                    'label' => '留言',
                    'enableSorting' => false,
                    'format' => 'html',
                    'contentOptions' => ['width'=>'50%'],
                    'value' => function ($model) {
                        $html = is_null(json_decode($model->note))?urldecode($model->note):json_decode($model->note);
                        if($model->msg){
                            $html .= '<br>';
                            $html .= '<div class="alert alert-info">'.$model->msg->content.'</div>';
                        }
                        return $html;
                    }
                ],

                [
                    'attribute' => 'created_at',
                    'label' => Yii::t('app', 'Created at'),
                    'format' => ['date', 'php:Y-m-d'],
                    'enableSorting' => false,
                    'contentOptions' => ['width'=>'10%'],
                ],


                [
                    'attribute' => 'status',
                    'enableSorting' => false,
                    'label' => Yii::t('app', 'Status'),
                    'format' => 'html',
                    'visible'=> (Yii::$app->requestedRoute !== 'user/notes-done'), //仅对某些用户展示
                    'value' => function ($model) {
                        $html = '/';
                        if($model->status == 0){
                            $html =  '<span class="label label-success">待处理</span>';
                        }else{
                            $html = '<span class="label label-danger">已处理</span>';
                        }
                        return $html;
                    }
                ],


                [
                    'header' => Yii::t('app', 'Operations'),
                    'class' => 'ua_backend\components\ActionColumn',
                    'contentOptions' => ['width'=>'10%'],
                    'visible'=>(Yii::$app->requestedRoute !== 'user/notes-done'),
                    'template' => '{send}',
                    'buttons' => [
                        'send' => function($url, $model){
                            $title = '<img style="width:30px;height:30px;margin-right:5px;" src="'.FILE_PATH.$model->user->avatar.'"/>';
                            $title = $title.json_decode($model->user->nickname);
//                            $url = 'send?post_id='.$model->id;
                            return Html::a('<span class="fs-13 fa fa-commenting"></span><span 
            class="fs-13 pd-l-2">通知</span>', '#', [
                                'link' => $url,
                                'data-title' => $title,
                                'data-id' => $model->id,  //所传参数
                                'data-uid' => $model->uid,  //所传参数
                                'data-toggle' => 'modal',
                                'data-target' => '#sendModal',
                                'class' => 'showModal',
                            ]);
                        },
                    ]
                ],
            ],
        ]); ?>
    </div>

<?php
//记录当前页面
$url = Yii::$app->request->getHostInfo().Yii::$app->request->url;
Yii::$app->user->setReturnUrl($url);
?>

<!-- 模态框（发送通知） -->
<div class="modal fade" id="sendModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title flex align-center"><div>回复消息</div> <div class="pd-lr-10">-</div> <div class="userInfo"></div></h4>
            </div>
            <div class="modal-body">
                <input class="form-control uid" type="hidden" name="uid" />
                <input class="form-control relid" type="hidden" value="0" name="relid" />
                <input class="form-control title" value="您提交的意见反馈已被回复" type="text" name="title" placeholder="消息标题（微信）"/>
                <div class="space20"></div>
                <textarea class="form-control content" rows="3" placeholder="回复内容（小程序内）"></textarea>
                <div class="space10"></div>
                <div class="fs-12 text-right">
                    标题剩余
                    <span class="text-red" id="wxTitle">8</span>个字符
                </div>
            </div>
            <div class="modal-footer">
                <div  style="float: left; line-height: 34px;" class="status">提示消息</div>
                <div style="float: right;" class="right-align"><button type="button" class="send btn btn-warning">发送</button></div>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>
<!-- /.modal -->

<script src="/js/jquery-2.2.3.min.js?v=1.0"></script>
<script src="/js/bootstrap.min.js"></script>
<script>
    $("#sendModal").on("show.bs.modal", function(e) {
        var link = $(e.relatedTarget)
        // console.log(link.attr("data-id"))
        $(this).find(".modal-body .uid").val(link.attr("data-uid"));
        $(this).find(".modal-title .userInfo").html(link.attr("data-title"));
        $(this).find(".modal-body .title").val('您提交的意见反馈已被回复');
        $(this).find(".modal-body .relid").val(link.attr("data-id"));
        $(this).find(".modal-body .content").val('');
        $(this).find(".modal-footer .status").empty();
    });

    $("#sendModal .title").keyup(function(){
        var len = $(this).val().length;
        if(len > 19){
            $(this).val($(this).val().substring(0,20));
        }
        var num = 20 - len;
        $("#wxTitle").text(num);
    });


    $(".send").on('click',function () {
        console.log('点击发送按钮')
        var uid = $("#sendModal .uid").val()
        var relid = $("#sendModal .relid").val()
        var act = 'reply'
        var title = $("#sendModal .title").val()
        var content = $("#sendModal .content").val()

        // console.log(relid)

        var errIndex = [40003,40037,43101,47003,41030]
        var errMsg = ['用户ID为空或者不正确',
            '订阅模板id为空不正确',
            '用户拒绝接受消息',
            '模板参数不准确，可能为空或者不满足规则',
            'page路径不正确']

        if(title == '' || content==''){
            $('.modal-footer .status').html('<span class="text-red">请填写要发送的消息</span>')
            return
        }

        var data = {uid: uid, rel_id: relid, act: act, title: title, content: content}
        // console.log(data)
        $.ajax({
            type: 'POST',
            url: './send-msg',
            data: data,
            dataType: 'json',
            beforeSend: function(){
                console.log('开始发送')
                $('.modal-footer .status').html('<span class="text-gray">正在发送..</span>')
            },
            success: function(res){
                console.log('发送成功')
                console.log(res)
                console.log(res.errcode)
                console.log(res.errmsg)

                if(res.errmsg=="ok"){
                    $('.modal-footer .status').html('<span class="text-green">发送成功</span>')
                }else{
                    var index = errIndex.indexOf(res.errcode)
                    $('.modal-footer .status').html('<span class="text-red">#'+res.errcode+'微信通知失败，'+errMsg[index]+'</span>')
                }

                window.location.reload();
            }
        });
    })
</script>
